package com.BGR.controller;

import com.BGR.common.R;
import com.BGR.entity.UserPhoto;
import com.BGR.service.UpUserPhotoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName UpUserPhotoController
 * @Date 2022/11/3 16:44
 * @Author xuxiaoran
 * @Description
 */
@RestController
@RequestMapping("/photo")
public class UpUserPhotoController {

    @Autowired
    private UpUserPhotoService upUserPhotoService;

    /**
     * 上传图像
     * @param file 图像
     * @param userId    用户Id
     * @return R
     */
    @PostMapping("/savePhoto")
    public R loadPhoto(@RequestParam MultipartFile file,
                       @RequestParam Long userId) throws IOException {
        //填充数据
        UserPhoto upUserPhoto = new UserPhoto();
        upUserPhoto.setUserId(userId);
        upUserPhoto.setImgByte(file.getBytes());

        //数据新增
        upUserPhotoService.save(upUserPhoto);
        return R.ok();
    }

    /**
     * 获取头像
     * @param userId 用户Id
     * @param response  HttpServletResponse
     * @return  R
     */
    @GetMapping("/getPhoto")
    public R getPhoto(@RequestParam Long userId, HttpServletResponse response) throws IOException {
        //查询该userId对应的图像
        UserPhoto userPhoto = upUserPhotoService
                .getOne(new QueryWrapper<UserPhoto>().eq("user_id", userId));

        byte[] imgByte = userPhoto.getImgByte();

        InputStream inputStream = new ByteArrayInputStream(imgByte);
        response.setContentType("image/*");

        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while((len = inputStream.read(buf,0,1024)) != -1){
            outputStream.write(buf,0,len);
        }
        outputStream.flush();
        outputStream.close();

        return R.ok();

    }

}
